<template>
	<view class="container">
		<view class=baby_image>
			<van-swipe class="my-swipe" :autoplay="2000" indicator-color="white">
			  <van-swipe-item v-for="image in images" :key="image">
			     <image class="img" :src="image" />
			   </van-swipe-item>
			</van-swipe>
		</view>
		<view class="title" >
			我的宝宝
		</view>
		<van-contact-card type="add" @click="showEdit=true;submitType='add'" add-text="添加宝宝"/>
		<view class="baby_card" v-for="(baby, index) in babyList" :key="index">
		      <van-card
				 :tag="baby.nickname"
		        :thumb="baby.image"
		        :title="baby.name"
		        :desc="baby.age"
		      >
		        <template #tags>
		          <van-tag v-for="(nature, index) in baby.nature" :key="index" type="warning">{{ nature }}</van-tag>
		        </template>
		        <template #footer>
		          <van-button size="mini" type="primary" @click="edit(baby.id)">编辑</van-button>
		          <van-button size="mini" type="danger" @click="delBaby(baby.id)">删除</van-button>
		        </template>
		      </van-card>
		    </view>
			<view style="height: 80rpx;"></view>
	</view>
	<van-form>
	<van-dialog v-model:show="showEdit" title="宝宝详情" show-cancel-button @confirm="handleConfirm" :before-close="validate" @cancel="cancel">
	  <van-cell-group inset>
	  	    <van-field
	  	      v-model="formData.name"
	  	      name="姓名"
	  	      label="姓名"
	  	      placeholder="输入宝宝姓名"
	  	      
	  	    />
	  	    <van-field
	  	      v-model="formData.nickname"
	  	      name="昵称"
	  	      label="昵称"
	  	      placeholder="输入宝宝昵称"
	  	      :rules="[{ required: true, message: '请填写昵称' }]"
	  	    />
			
	  	  <van-field
	  	    v-model="formData.age"
	  	    name="年龄"
	  	    label="年龄"
	  	    placeholder="输入宝宝年龄"
	  	    :rules="[{ required: true, message: '请填写年龄' }]"
	  	  />
	  	  
	  	  <van-field name="uploader" label="宝宝照片">
			  
	  	    <template #input>
	  	      <van-uploader v-model="formData.image"  :max-count="1" :after-read="afterRead" />
	  	    </template>
	  	  </van-field>
	  </van-cell-group>
	</van-dialog>
	</van-form>
</template>

<script setup>
	import { ref, onMounted } from 'vue';
	import { onPullDownRefresh } from '@dcloudio/uni-app';
	import { Swipe, SwipeItem ,Card, ContactCard,Dialog, Field, CellGroup,Uploader ,Toast} from 'vant';
	import BabyEditForm from './BabyEditForm.vue'
	import {getBabyInfoListApi,addBaby,getBabyInfoById,deleteBabyById,updateBabyInfoById} from '../../apis/babyApi.js'
	 const images =ref([]) 
		
		const babyList=ref([])
		const showEdit=ref(false)
		const submitType=ref('add')
		const isUpdateImage=ref(false)
		const formData=ref({
			id:'',
			name:'',
			nickname:'',
			image:[],
			age:'',
		})
		//删除宝宝
		const delBaby = async(id) => {
		  Dialog.confirm({
		    title: '删除宝宝',
		    message: '确定要删除宝宝的所有数据吗？',
		  })
		  .then(async() => {
			  console.log('删除！！！！！')
			const res= await deleteBabyById(id)
			if(res==='ok'){
				Toast('删除成功！')
			}
			refresh()
		  });
		};
		
		const getBabyList=async()=>{
			const res = await getBabyInfoListApi()
			babyList.value=res.data
			for(let i=0;i<babyList.value.length;i++){
				images.value.push(babyList.value[i].image)
			}
			
		}
		const refresh=async()=>{
			Toast.loading({
			  message: '加载中...',
			  forbidClick: true,
			  duration:300
			});
		 await	getBabyList()
		}
		
	//上传文件类型校验
	const afterRead=(file)=>{
		if(file.file.type!=='image/png'&&file.file.type!=='image/jpg'&&file.file.type!=='image/jpeg'){
			Toast('非法文件！')
			formData.value.image=[]
		}
		console.log(file)
	}
	
	const isCancel=ref(false)
	//表单校验 
	const validate=()=>{
		console.log(isCancel.value)
		if(isCancel.value){
			isCancel.value=false
			return true
		}
		if(formData.value.nickname===''){
			Toast('请填写宝宝昵称！')
			
			return false
		}
		if(formData.value.age===''){
			Toast('请填写宝宝年龄！')
			
			return false
		} 
		return true
	}
		
	//置空
	const doEmpt=()=>{
		formData.value.id=''
		formData.value.name=''
		formData.value.nickname=''
		formData.value.age=''
		formData.value.image=[]
	}
	//关闭表单
	const cancel=()=>{
		isCancel.value=true
	}
	//提交表单-添加宝宝
	const handleConfirm =async () => {
		
	   if(formData.value.nickname&&formData.value.age){
		   console.log('通过！')
		  // 执行表单提交逻辑
		  const base64Image=ref('')
		  
		  if(submitType.value==='add'){
			  if(formData.value.image.length>0){
			  			 base64Image.value  = formData.value.image[0].content.split(',')[1];
			  			 
			  }
			  const res= await addBaby({
			  			  name:formData.value.name,
			  			  nickname:formData.value.nickname,
			  			  age:formData.value.age,
			  			  image:base64Image.value
			  })
			  if(res==='ok'){
			  	Toast('添加成功！')
			  }
		  }else if(submitType.value==='edit'){
			  // console.log(formData.value.image[0])
			  const image=ref()
			  if(formData.value.image.length>0&&formData.value.image[0].raw){
				  console.log('未修改')
			  	  image.value=null
			  }else{
				  image.value=formData.value.image[0].content.split(',')[1];
			  }
			  const res= await updateBabyInfoById({
						  id:formData.value.id,
			  			  name:formData.value.name,
			  			  nickname:formData.value.nickname,
			  			  age:formData.value.age,
			  			  image:image.value,
			  })
			  if(res==='ok'){
			  	Toast('修改成功！')
			  }
		  }
		 
		  doEmpt()
		  refresh()
	   }
	   
	}
	//获取宝宝信息
	const getEcho=async(id)=>{
		const res=await getBabyInfoById(id)
		console.log(res)
		formData.value.id=res.data.id
		formData.value.name=res.data.name
		formData.value.nickname=res.data.nickname
		formData.value.age= res.data.age
		formData.value.image[0] = { name: "0", percentage: 0, status: "success", size: 0, raw: null, uid: null, url: res.data.image }
		 
		  const jsonData = JSON.stringify(formData.value.image[0])
		  const content = new Blob([jsonData], { type: 'image/jpg' })
		  const filename = 'example.jpeg'
		  const file = new File([content], filename, { type: 'image/jpg' })
		  formData.value.image[0].raw = file
	}
	//编辑宝宝
	const edit=async(id)=>{
		doEmpt()
		showEdit.value=true
		submitType.value='edit'
		
		await getEcho(id)
		
	}

		onPullDownRefresh(async()=>{
			
			await refresh()
			console.log('刷新完毕')
			uni.stopPullDownRefresh()
		})
		onMounted(async()=>{
			await getBabyList()
		})
		
</script>

<style scoped>
	.container{
		background-color: snow;
		height: 100vh;
	}

	.my-swipe{
		width: 716rpx;
		height: 400rpx;
		border-radius: 20rpx;
		margin: 0 0 0 17rpx;
		box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
	}
	.img{
		width: 100%;
		height: 100%;
	}
	
.title{
	display: flex;
	justify-content: center;
	align-items: center;
	height: 80rpx;
	/* background-color:honeydew; */
	color: rgba(43, 66, 76, 1.0);
	font-size: 18px;
	border-radius: 10px;
}
.baby_card{
	width: 716rpx;
	margin: 10rpx 0 0 17rpx;
	border-radius: 40rpx;
	box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
}
</style>
